﻿using System;
using System.Net;
using System.Diagnostics;

using SharedGenomics.Workbench.Core;

namespace SharedGenomics.Workbench.Services
{
    public class RemoteAnalysisResultsLocator : IAnalysisResultsLocator
    {
        public RemoteAnalysisResultsLocator(IDataService dataService, ILoginManager loginManager)
        {
            this.DataService = dataService;
            this.LoginManager = loginManager;
        }

        public Maybe<AnalysisResultsInfo> FindResultsForJob(int jobId)
        {
            //if there is no login, we cannot do anything except return nothing here...
            if (!this.LoginManager.IsLoggedIn)
            {
                return new Maybe<AnalysisResultsInfo>();
            }

            return this.DataService.GetJobResultsFileLocation(jobId).Bind(locationInfo =>
            {
                //get remote job filestream
                //create an execute web request for given output file uri and get the response stream
                HttpWebRequest request = this.CreateWebRequest(locationInfo.Location);
                var response = request.GetResponse();
                var responseStream = response.GetResponseStream();

                return new AnalysisResultsInfo(locationInfo.JobType, responseStream);
            });
        }

        private HttpWebRequest CreateWebRequest(Uri target)
        {
            Debug.Assert(this.LoginManager.IsLoggedIn);

            HttpWebRequest request = (HttpWebRequest)(HttpWebRequest.Create(target));
            request.Method = "GET";
            request.Timeout = 30000;                //30 seconds

            var loginCredentials = this.LoginManager.LoginCredentials;

            NetworkCredential netCred = loginCredentials.CreateNetworkCredential();
            CredentialCache credentialCache = new CredentialCache();
            credentialCache.Add(target, "NTLM", netCred);
            request.Credentials = credentialCache;

            return request;
        }

        private IDataService DataService { get; set; }
        private ILoginManager LoginManager { get; set; }
    }
}
